import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { User, UserRole } from '@/types'
import { authApi } from '@/services/auth'
import { envConfig } from '@/config/env'

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref<User | null>(null)
  const isLoggedIn = ref(false)
  const token = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)

  // 计算属性
  const userRole = computed(() => currentUser.value?.role || null)
  const isEnterprise = computed(() => userRole.value === UserRole.ENTERPRISE)
  const isSupervisor = computed(() => userRole.value === UserRole.SUPERVISOR)
  const isStudent = computed(() => userRole.value === UserRole.STUDENT)
  const isAdmin = computed(() => userRole.value === UserRole.ADMIN)
  const canPublishProject = computed(() => isEnterprise.value)
  const canApplyProject = computed(() => isSupervisor.value || isStudent.value)
  const canManageSystem = computed(() => isAdmin.value)

  // 模拟用户数据（开发环境使用，生产环境应该从API获取）
  const mockUsers = [
    {
      id: '1',
      username: 'enterprise1',
      role: UserRole.ENTERPRISE,
      name: '华为技术有限公司',
      email: 'hr@huawei.com',
      phone: '0755-12345678',
      organization: '华为技术有限公司',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z'
    },
    {
      id: '2',
      username: 'supervisor1',
      role: UserRole.SUPERVISOR,
      name: '张教授',
      email: 'zhang@sysu.edu.cn',
      phone: '020-12345678',
      department: '计算机科学与技术学院',
      researchDirection: ['人工智能', '机器学习', '计算机视觉'],
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z'
    },
    {
      id: '3',
      username: 'student1',
      role: UserRole.STUDENT,
      name: '李同学',
      email: 'li@sysu.edu.cn',
      phone: '020-87654321',
      department: '计算机科学与技术学院',
      researchDirection: ['人工智能', '深度学习'],
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z'
    },
    {
      id: '4',
      username: 'admin',
      role: UserRole.ADMIN,
      name: '管理员',
      email: 'admin@sysu.edu.cn',
      phone: '020-11111111',
      organization: '中山大学研究生院',
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z'
    }
  ]

  // 方法
  const login = async (username: string, password: string, role: string) => {
    try {
      // 根据环境配置决定使用真实API还是模拟登录
      if (envConfig.ENABLE_MOCK) {
        // 模拟登录逻辑
        const user = mockUsers.find(u => u.username === username && u.role === role)
        if (user) {
          currentUser.value = user
          isLoggedIn.value = true
          token.value = `mock-token-${Date.now()}`
          refreshToken.value = `mock-refresh-${Date.now()}`
          
          // 保存到本地存储
          localStorage.setItem('user', JSON.stringify(user))
          localStorage.setItem('token', token.value)
          localStorage.setItem('refreshToken', refreshToken.value)
          
          return { success: true, user }
        } else {
          return { success: false, message: '用户名、密码或角色错误' }
        }
      } else {
        // 真实API登录
        const response = await authApi.login({ username, password, role })
        
        if (response.success) {
          const { token: newToken, refreshToken: newRefreshToken, user } = response.data
          
          // 确保用户数据包含所有必需字段
          const fullUser: User = {
            id: user.id,
            username: user.username,
            role: user.role as UserRole,
            name: user.name,
            email: user.email,
            phone: (user as any).phone || '',
            avatar: user.avatar,
            organization: (user as any).organization || '',
            department: (user as any).department || '',
            researchDirection: (user as any).researchDirection || [],
            createdAt: (user as any).createdAt || new Date().toISOString(),
            updatedAt: (user as any).updatedAt || new Date().toISOString()
          }
          
          currentUser.value = fullUser
          isLoggedIn.value = true
          token.value = newToken
          refreshToken.value = newRefreshToken
          
          // 保存到本地存储
          localStorage.setItem('user', JSON.stringify(fullUser))
          localStorage.setItem('token', newToken)
          localStorage.setItem('refreshToken', newRefreshToken)
          
          return { success: true, user: fullUser }
        } else {
          return { success: false, message: response.message || '登录失败' }
        }
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { 
        success: false, 
        message: error.message || '登录失败，请重试' 
      }
    }
  }

  const logout = async () => {
    try {
      // 如果启用了真实API，调用退出登录接口
      if (!envConfig.ENABLE_MOCK && token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地状态
      currentUser.value = null
      isLoggedIn.value = false
      token.value = null
      refreshToken.value = null
      
      // 清除本地存储
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    }
  }

  const checkAuth = async () => {
    const savedUser = localStorage.getItem('user')
    const savedToken = localStorage.getItem('token')
    const savedRefreshToken = localStorage.getItem('refreshToken')
    
    if (savedUser && savedToken) {
      try {
        if (envConfig.ENABLE_MOCK) {
          // 模拟环境直接恢复状态
          currentUser.value = JSON.parse(savedUser)
          isLoggedIn.value = true
          token.value = savedToken
          refreshToken.value = savedRefreshToken
        } else {
          // 真实环境验证token有效性
          const response = await authApi.getCurrentUser()
          if (response.success) {
            currentUser.value = response.data
            isLoggedIn.value = true
            token.value = savedToken
            refreshToken.value = savedRefreshToken
          } else {
            // token无效，尝试刷新
            if (savedRefreshToken) {
              await refreshUserToken()
            } else {
              logout()
            }
          }
        }
      } catch (error) {
        console.error('验证认证状态失败:', error)
        logout()
      }
    }
  }

  const refreshUserToken = async () => {
    if (!refreshToken.value) {
      logout()
      return false
    }

    try {
      const response = await authApi.refreshToken({ refreshToken: refreshToken.value })
      if (response.success) {
        const { token: newToken, refreshToken: newRefreshToken } = response.data
        token.value = newToken
        refreshToken.value = newRefreshToken
        
        localStorage.setItem('token', newToken)
        localStorage.setItem('refreshToken', newRefreshToken)
        
        return true
      } else {
        logout()
        return false
      }
    } catch (error) {
      console.error('刷新token失败:', error)
      logout()
      return false
    }
  }

  const updateUserInfo = (userInfo: Partial<User>) => {
    if (currentUser.value) {
      currentUser.value = { ...currentUser.value, ...userInfo }
      localStorage.setItem('user', JSON.stringify(currentUser.value))
    }
  }

  // 模拟注册功能
  const register = async (userData: any) => {
    try {
      if (envConfig.ENABLE_MOCK) {
        // 模拟注册过程
        await new Promise(resolve => setTimeout(resolve, 1000))
        return { success: true, message: '注册成功' }
      } else {
        // 真实API注册
        const response = await authApi.register(userData)
        return response
      }
    } catch (error: any) {
      return { success: false, message: error.message || '注册失败，请重试' }
    }
  }

  // 初始化时检查认证状态
  checkAuth()

  return {
    // 状态
    currentUser,
    isLoggedIn,
    token,
    refreshToken,
    
    // 计算属性
    userRole,
    isEnterprise,
    isSupervisor,
    isStudent,
    isAdmin,
    canPublishProject,
    canApplyProject,
    canManageSystem,
    
    // 方法
    login,
    logout,
    checkAuth,
    updateUserInfo,
    register,
    refreshUserToken
  }
})
